package com.ry.jwtexp.advice;

import com.ry.jwtexp.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.File;

/**
 * @Author ry
 * @Description  返回消息的统一处理
 * 从spring mvc 4.0起引入RequestBodyAdvice和ResponseBodyAdvice这两个接口之后，
 * 之前描述的代码重复问题就可以彻底解决了。其中，RequestBodyAdvice主要用于对请求参数的增强处理。
 * 而ResponseBodyAdvice用于对响应参数的增强处理。所以，为了使返回的数据格式统一，很明显，
 * 我们只需要自己写一个实现ResponseBodyAdvice接口的类，并作为一个bean对象注入spring容器中即可。
 * https://blog.csdn.net/nmgrd/article/details/77870277
 * @Date 2020/9/1 11:13
 */
@ControllerAdvice
@Slf4j
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        log.debug("MyResponseBodyAdvice ==>supports:"+ converterType);
        log.debug("MyResponseBodyAdvice ==>supports:"+ methodParameter.getClass());
        log.debug("MyResponseBodyAdvice ==>supports:" + MappingJackson2HttpMessageConverter.class
                .isAssignableFrom(converterType));
        return MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body == null){
            return body;
        }
        if(body instanceof AjaxResult || body instanceof String){
            return body;
        } else if (body instanceof File){
            return body;
        } else{
            log.debug("MyResponseBodyAdvice==>beforeBodyWrite:"+ mediaType+","+body);
            AjaxResult result = new AjaxResult(true);
            result.setCode(HttpStatus.OK.value());
            result.setData(body);
            return body;
        }
    }
}
